package com.biyabi.service.impl;

import com.biyabi.dao.*;
import com.biyabi.entity.*;
import com.biyabi.pojo.*;
import com.biyabi.service.OrderService;
import com.biyabi.service.ProductService;
import com.github.pagehelper.PageHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AddressMapper addressMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductService productService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SkuMapper skuMapper;
    @Resource
    private SizeMapper sizeMapper;
    @Resource
    private ColorMapper colorMapper;

    //用户创建订单
    @Override
    public OrderPojo add(Cart cart, String addressid, String userId) {
        Order order = new Order();
        OrderPojo orderPojo = new OrderPojo();
        order.setId(UUID.randomUUID().toString());
        String dateStr = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        order.setOrderid(dateStr+redisTemplate.opsForValue().increment("OrderId",1).toString());
        order.setCreatedate(new Date());
        order.setExpiry(3);
        order.setFreight(10.0);
        order.setPostage(90.0);
        order.setTaxes(40.0);
        if(!StringUtils.isEmpty(order.getCouponid())){
            Integer quota = couponMapper.selectByPrimaryKey(order.getCouponid()).getQuota();
            order.setTotalprice(cart.getTotalPrice()-quota);
        }else{
            order.setTotalprice(cart.getTotalPrice());
        }
        order.setIsexpose(0);
        order.setAddressid(addressid);
        order.setUserid(userId);
        order.setStatus(0);//未支付
        orderMapper.insert(order);
        orderPojo.setOrder(order);
        orderPojo.setAddress(addressMapper.selectByPrimaryKey(addressid));
        ArrayList<OrderItemPojo> orderItemPojos = new ArrayList<>();
        for(Map.Entry<String, CartItem> entry : cart.getCartItems().entrySet()){
            OrderItem orderItem = new OrderItem(UUID.randomUUID().toString(),entry.getValue().getSum(),entry.getValue().getSum()*entry.getValue().getSkuPojo().getOriginPrice()*entry.getValue().getSkuPojo().getDiscount(),entry.getValue().getProduct().getId(),entry.getValue().getSkuPojo().getId(),order.getId());
            orderItemMapper.insert(orderItem);
            OrderItemPojo orderItemPojo = new OrderItemPojo();
            orderItemPojo.setOrderItem(orderItem);
            orderItemPojo.setProductPojo(productService.beanToPojo(entry.getValue().getProduct()));
            orderItemPojos.add(orderItemPojo);
        }
        orderPojo.setOrderItemPojos(orderItemPojos);
        orderPojo.setUser(userMapper.selectByPrimaryKey(userId));
        return orderPojo;
    }
    //用户取消订单
    @Override
    public void delete(String id) {
        OrderItemExample example = new OrderItemExample();
        example.createCriteria().andOrderidEqualTo(id);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItems) {
            orderItemMapper.deleteByPrimaryKey(orderItem.getId());
        }
        orderMapper.deleteByPrimaryKey(id);
    }
    //管理员查询所有订单
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public OrderData selectAll(Integer currentPage, Integer pageSize,String columnName,String columnValue ) {
        currentPage = currentPage == null ? 1:currentPage;
        pageSize= pageSize== null ? 5:pageSize;
        OrderExample orderExample = new OrderExample();

        if(columnName!=null && columnValue!=null){
            switch (columnName){
                case "orderId":
                    orderExample.createCriteria().andOrderidLike("%"+columnValue+"%");
                    break;
                case "phone":
                    AddressExample example1 = new AddressExample();
                    example1.createCriteria().andPhoneLike("%"+columnValue+"%");
                    List<Address> addresses = addressMapper.selectByExample(example1);
                    List<String> addressids = new ArrayList<>();
                    for (Address address : addresses) {
                        addressids.add(address.getId());
                    }
                    if(addressids.size()>0)
                        orderExample.createCriteria().andAddressidIn(addressids);
                    else
                        orderExample.createCriteria().andIdIsNull();
                    break;
                case "nickname":
                    UserExample example = new UserExample();
                    example.createCriteria().andNicknameLike("%"+columnValue+"%");
                    List<User> users = userMapper.selectByExample(example);
                    List<String> userIds = new ArrayList<>();
                    for (User user : users) {
                        userIds.add(user.getId());
                    }
                    if(userIds.size()>0)
                        orderExample.createCriteria().andUseridIn(userIds);
                    else
                        orderExample.createCriteria().andIdIsNull();
                    break;
                case "status":
                    int sta = 0;
                    switch (columnValue){
                        case "已支付":
                            sta = 1;
                            break;
                        case "已发货":
                            sta = 2;
                            break;
                        case "已签收":
                            sta = 3;
                            break;
                        case "交易完成":
                            sta = 4;
                            break;
                    }
                    orderExample.createCriteria().andStatusEqualTo(sta);
                    break;
                case "consignee":
                    AddressExample example2 = new AddressExample();
                    example2.createCriteria().andConsigneeLike("%"+columnValue+"%");
                    List<Address> addresses1 = addressMapper.selectByExample(example2);
                    List<String> addressids1 = new ArrayList<>();
                    for (Address address : addresses1) {
                        addressids1.add(address.getId());
                    }
                    if(addressids1.size()>0)
                        orderExample.createCriteria().andAddressidIn(addressids1);
                    else
                        orderExample.createCriteria().andIdIsNull();
                    break;

            }
        }



        OrderData orderData = new OrderData();
        int i = orderMapper.countByExample(orderExample);
        PageHelper.startPage(currentPage,pageSize);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        orderData.setTotal(i);
        ArrayList<OrderPojo> orderPojos = new ArrayList<>();
        for (Order order : orders) {
            orderPojos.add(beanToPojo(order));
        }
        orderData.setRows(orderPojos);
        return orderData;

    }
    //用户查询订单
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<OrderPojo> selectByUserId(String userId) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andUseridEqualTo(userId);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        ArrayList<OrderPojo> orderPojos = new ArrayList<>();
        for (Order order : orders) {
            orderPojos.add(beanToPojo(order));
        }
        return orderPojos;
    }
    //管理员修改订单状态
    @Override
    public void updateStatus(String orderId,Integer status) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(status);
        orderMapper.updateByPrimaryKey(order);
    }
    //用户晒单
    @Override
    public void expose(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setIsexpose(1);
        orderMapper.updateByPrimaryKey(order);
    }

    //工具方法
    public OrderPojo beanToPojo(Order order){
        OrderPojo orderPojo = new OrderPojo();
        OrderItemExample example = new OrderItemExample();
        example.createCriteria().andOrderidEqualTo(order.getId());
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        orderPojo.setOrder(order);
        orderPojo.setAddress(addressMapper.selectByPrimaryKey(order.getAddressid()));
        ArrayList<OrderItemPojo> orderItemPojos = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            OrderItemPojo orderItemPojo = new OrderItemPojo();
            orderItemPojo.setOrderItem(orderItem);
            SkuPojo skuPojo = new SkuPojo();
            Sku sku = skuMapper.selectByPrimaryKey(orderItem.getSkuid());
            skuPojo.setId(sku.getId());
            skuPojo.setDiscount(sku.getDiscount());
            skuPojo.setWeight(sku.getWeight());
            skuPojo.setSize(sizeMapper.selectByPrimaryKey(sku.getSizeid()).getName());
            skuPojo.setOriginPrice(sku.getOriginprice());
            skuPojo.setImage(sku.getImage());
            skuPojo.setCount(sku.getCount());
            skuPojo.setColor(colorMapper.selectByPrimaryKey(sku.getColorid()).getName());
            orderItemPojo.setSkuPojo(skuPojo);
            orderItemPojo.setProductPojo(productService.beanToPojo(productMapper.selectByPrimaryKey(orderItem.getProductid())));
            orderItemPojos.add(orderItemPojo);
        }
        orderPojo.setOrderItemPojos(orderItemPojos);
        orderPojo.setUser(userMapper.selectByPrimaryKey(order.getUserid()));
        return orderPojo;
    }
}
